package com.shenma2009.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenma2009.domain.ResultResponse;
import com.shenma2009.pojo.TbRoom;
import com.shenma2009.service.TbRoomService;
import com.shenma2009.mapper.TbRoomMapper;
import com.shenma2009.utils.RandomUtils;
import com.shenma2009.utils.TxLiveUtils;
import com.shenma2009.vo.IdVo;
import com.shenma2009.vo.PageVo;
import com.shenma2009.vo.TbRoomVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
* @author 33509
* @description 针对表【tb_room(直播房间表)】的数据库操作Service实现
* @createDate 2023-05-09 14:09:37
*/
@Service
public class TbRoomServiceImpl extends ServiceImpl<TbRoomMapper, TbRoom>
    implements TbRoomService{

    @Override
    public ResultResponse add(TbRoomVo tbRoomVo) {
        TbRoom tbRoom = new TbRoom();

        // 拷贝房间属性
        BeanUtils.copyProperties(tbRoomVo, tbRoom);

        String roomNo = RandomUtils.random().randomIntCode(6);
        tbRoom.setRoomNo(roomNo);

        // 生成推流和拉流地址
        String pushUrl = TxLiveUtils.makePushUrl(roomNo, 60 * 24);
        tbRoom.setPushUrl(pushUrl);

        String playUrl = TxLiveUtils.makePlayUrl(roomNo);
        tbRoom.setPlayUrl(playUrl);

        save(tbRoom);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse listByPage(PageVo pageVo) {
        Page<TbRoom> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());

        QueryWrapper<TbRoom> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(TbRoom::getRoomId);

        Page<TbRoom> tbRoomPage = this.page(page, wrapper);

        // 对象转VO

        Page<TbRoomVo> tbRoomVoPage = new Page<>();
        BeanUtils.copyProperties(tbRoomPage, tbRoomVoPage);

        List<TbRoomVo> collect = tbRoomPage.getRecords().stream().map(item -> {
            TbRoomVo tbRoomVo = new TbRoomVo();
            BeanUtils.copyProperties(item, tbRoomVo);
            return tbRoomVo;
        }).collect(Collectors.toList());

        tbRoomVoPage.setRecords(collect);

        return ResultResponse.SUCCESS(tbRoomVoPage);
    }

    @Override
    public ResultResponse get(IdVo idVo) {
        //-- 判断房间是否存在
        TbRoom tbRoom = getById(idVo.getId());
        if(tbRoom == null) {
            return ResultResponse.FAILED(404, "房间不存在");
        }

        //-- 获取房间信息
        TbRoomVo tbRoomVo = new TbRoomVo();
        BeanUtils.copyProperties(tbRoom, tbRoomVo);

        return ResultResponse.SUCCESS(tbRoomVo);
    }
}




